package com.api.v1.action;


import com.api.v1.service.SeckillGoodsService;
import com.pojo.Seckillgoods;
import com.vo.ResponseBean;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/seckillGoods/")
@CrossOrigin("*")
public class SeckillGoodsAction {

    @Autowired
    private SeckillGoodsService  seckillGoodsService;

    @Autowired
    private RedissonClient  redissonClient;

    @Autowired
    private RedisTemplate  redisTemplate;  //spring data  redis

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/getAll")
    public ResponseBean getAll()
    {
       List list =  seckillGoodsService.getAllSeckillGoods();

       // redisTemplate.boundValueOps("goods").set(list);

       return new ResponseBean(200,"成功",list);
    }

    @RequestMapping("/go")
    public ResponseBean go(Long sid)
    {
        //加锁----------------------------------------
        RLock  rLock = redissonClient.getLock("seckillLock");
        rLock.lock(100, TimeUnit.MILLISECONDS);
        //根据秒杀编号查秒杀对象,这里使用自动缓存
        Seckillgoods seckillgoods = seckillGoodsService.findById(sid);
        //根据秒杀对象查库存
        long kuchun = seckillgoods.getKuchun();
        //判断库存,//减库存
        if (kuchun>0)
        {
            kuchun--;
        }
        //写订单,略,,发送消息给消息队列，消息队列收到消息后，写订单
        String msg =sid+""; //最好拼id和用户信息
        //交换机名称， 绑定key, 发送的内容
        rabbitTemplate.convertAndSend("directExchange","miaosha",msg);

        //----------------解锁


        rLock.unlock();

        //返回
        return new ResponseBean(200,"成功",null);
    }

    /**
     * 这种方式不好
     * @param sid
     * @return
     *
     *    1.线程安全（单服务器)   synchronized只锁住当前一个服务器这个方法（排队)
     *    2.分布式锁(集群环境)   可以使用 a) redis的redisson b)zookeeper
     */
    @RequestMapping("/goOLD")
    public  ResponseBean goOLD(Long sid)
    {
        //根据秒杀编号查秒杀对象,查数据库性能低
        Seckillgoods seckillgoods = seckillGoodsService.getById(sid);
        //根据秒杀对象查库存
        long kuchun = seckillgoods.getKuchun();
        //判断库存,//减库存,并发访问会库存会超卖
        if (kuchun>0)
        {
            kuchun--;
        }
        //写订单,略,性能更低了

        //返回
        return new ResponseBean(200,"成功",null);
    }
}
